import json
import re

from pymysql import *
import requests
import time
import sendmail


class QianDao():

    def login(self,user,password):
        """模拟登录OA并获取前一工作日打卡记录"""
        headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36"}
        formdata = {
            "login_username": user,
            "login_password": password,
        }
        url = "http://192.168.3.198:8699/seeyon/main.do?method=login"
        # 模拟登录OA并保存cookie信息
        ssion = requests.Session()
        responseRes = ssion.post(
            url,
            headers = headers,
            data= formdata
        )
        # print(responseRes.request.headers.get("Cookie"))
        # print(responseRes.url)
        # print(responseRes.status_code)

        # 获取当前时间 年、月
        # 获取抓取打卡信息的参数信息
        # 获取当前的日期，判断是否是1号，如果是抓取上个月的打卡信息，如果不是正常进行
        shijian = []
        year = str(time.localtime().tm_year)
        # print(year)
        shijian.append(year)
        day_num = int(time.localtime().tm_mday)
        if day_num == 1:
            mon = int(time.localtime().tm_mon) - 1
        else:
            mon = str(time.localtime().tm_mon)
        shijian.append(mon)
        a = "1173708294355566692"
        shijian.append(a)
        # print(shijian)
        data = {"managerMethod": "PersonageKqShow"}
        data["arguments"] = str(shijian)
        # print(data)
        NETWORK_STATUS = True # 判断请求状态
        res = ''
        try:
            res = ssion.post("http://192.168.3.198:8699/seeyon/ajax.do?method=ajaxAction&managerName=personageKqManage",data=data, timeout=5)
        except:
            # global NETWORK_STATUS
            print("请求超时")
            NETWORK_STATUS = False  # 请求超时改变状态
            if NETWORK_STATUS==False:
                """请求超时"""
                for i in range(1,3):
                    ssion = requests.Session()
                    responseRes = ssion.post(
                        url,
                        headers=headers,
                        data=formdata
                    )
                    try:
                        res = ssion.post(
                            "http://192.168.3.198:8699/seeyon/ajax.do?method=ajaxAction&managerName=personageKqManage",
                            data=data, timeout=5)
                    except:
                        print("请求超时")
                        continue
                    else:
                        # return res
                        break
                        # return res

        """oa退出登录url:http://192.168.3.198:8699/seeyon/main.do?method=logout"""
        # 退出本次登录
        ssion.get("http://192.168.3.198:8699/seeyon/main.do?method=logout",headers = headers)
        # print(count)
        # 获取签到数据
        try:
            count = res.content.decode()
        except:
            print("网络异常，获取数据失败！")
            return
        try:
            count = eval(re.search(r"content:(.*)\}",count).group(1))
        except:
            print("用户名或密码错误，获取数据失败！")
            return
            # print(count)
        for zhou_list in count:

            for day in zhou_list:
                item = {}
                item['riqi'] = int(day['name']) if day['name'] else 0
                # 获取当前日期天数
                a = int(time.localtime().tm_mday)
                # a = 5
                b = item['riqi'] - a
                qiandao = re.split(r"<br/>|</br>", day['team'])
                item['qiandao_dizhi'] = qiandao[0]
                if b == -1  and item['qiandao_dizhi'] != '休息' and item['qiandao_dizhi'] != '':
                    item['qiandao_zaoshang'] = qiandao[1]
                    item['qiandao_zaoxia'] = qiandao[2]
                    item['qiandao_xiawushang'] = qiandao[3]
                    item['qiandao_xiawuxia'] = qiandao[4]
                    return item
                elif b > 0:
                    mon = int(time.localtime().tm_mon) - 1
                    if mon in [1,3,5,7,8,10,12]:
                        if item['riqi'] == 31:
                            item['qiandao_zaoshang'] = qiandao[1]
                            item['qiandao_zaoxia'] = qiandao[2]
                            item['qiandao_xiawushang'] = qiandao[3]
                            item['qiandao_xiawuxia'] = qiandao[4]
                            return item
                    elif mon in [4,6,9,11]:
                        if item['riqi'] == 30:
                            item['qiandao_zaoshang'] = qiandao[1]
                            item['qiandao_zaoxia'] = qiandao[2]
                            item['qiandao_xiawushang'] = qiandao[3]
                            item['qiandao_xiawuxia'] = qiandao[4]
                            return item
                    else:
                        if item['riqi'] == 28:
                            item['qiandao_zaoshang'] = qiandao[1]
                            item['qiandao_zaoxia'] = qiandao[2]
                            item['qiandao_xiawushang'] = qiandao[3]
                            item['qiandao_xiawuxia'] = qiandao[4]
                            return item

    # 判断是否打卡异常
    def send_email(self,user,password,to_addr):
        item = self.login(user,password)
        # print(item)
        print(item)
        if item:
            if item['qiandao_dizhi'] != '休息' and item['qiandao_dizhi'] != '':
                qiandao_zaoshang = re.findall(r"缺勤|迟到|早退",item['qiandao_zaoshang'])
                qiandao_zaoxia = re.findall(r"缺勤|迟到|早退",item['qiandao_zaoxia'])
                qiandao_xiawushang = re.findall(r"缺勤|迟到|早退",item['qiandao_xiawushang'])
                qiandao_xiawuxia = re.findall(r"缺勤|迟到|早退",item['qiandao_xiawuxia'])
                if qiandao_zaoshang or qiandao_zaoxia or qiandao_xiawushang or qiandao_xiawuxia:
                    work_time = time.strftime('%Y-%m-')  # 工作时间
                    count = "您上个工作日的签到打卡记录异常，请登录OA系统确认！http://1.192.217.143:8699/seeyon/index.jsp\n\n"+"" \
                            "工作日期："+str(work_time)+str(item["riqi"])+"\n工作地点："+item["qiandao_dizhi"]+"\n上午:\n\t"+"\t"+item["qiandao_zaoshang"]+"\n\t"+item['qiandao_zaoxia']+"" \
                            "\n\n下午:\n\t"+"\t"+item['qiandao_xiawushang']+"\n\t"+item['qiandao_xiawuxia']
                    #to_addr = user+'@topnet.net.cn'
                    to_addr = to_addr
                    # print(to_addr)
                    try:
                        server = sendmail.SendMail().send(count,to_addr)
                    except:
                        print(user+'签到异常，邮件发送失败！！\n'+count)
                    print(user+"签到异常，邮件发送ok!!!")
                    # server.quit()
                else:
                    print(time.strftime('%Y-%m-%d %H:%M:%S'),user+"签到打卡无异常！")
                    return
            else:
                print(time.strftime('%Y-%m-%d %H:%M:%S'),user+"签到打卡无异常！")
                return
        else:
            print(time.strftime('%Y-%m-%d %H:%M:%S'), user + "前一天休息！！！")
            return
            #[08:50上班]-<font', 'qiandao_zaoxia': 'color="red">迟到：09:40</font>
        #[11:50下班]-签退：12:19

if __name__ == '__main__':
    try:
        conn = connect(host='192.168.3.191',
                       port=3306,
                       database='yuangong',
                       user='root',
                       password='abcd@1234',
                       charset="utf8",
                       )
        cs = conn.cursor()
        sql = "select name,password,email from user_name"
        cs.execute(sql)
        count = cs.fetchall()
        print(count)
    except:
        print("服务器连接失败！！！")
        count1 = [('xieyabin', 'xyb.0926','xieyabin@topnet.net.cn')]
        # ,('heyin', 'heyin6525267','heyin@topnet.net.cn'), ('chenhuachao', 'chc900516','chenhuachao@topnet.net.cn'),('liguoqiang', '123456','liguoqiang@topnet.net.cn'), ('wangshengnan', 'teng710','wangshengnan@topnet.net.cn')
        for count in count1:
            qiandao = QianDao()
            qiandao.send_email(count[0], count[1],count[2])
    else:
        for i in count:
            qiandao = QianDao()
            qiandao.send_email(i[0], i[1],i[2])
